package lion.se.lucene.index;

import java.util.Date;
import java.util.Map;

import lion.dev.lang.MapJ;
import lion.dev.text.Formater;

import org.apache.lucene.document.Document;
import org.apache.lucene.document.DoubleField;
import org.apache.lucene.document.Field;
import org.apache.lucene.document.FieldType;
import org.apache.lucene.document.StringField;
import org.apache.lucene.document.TextField;
import org.apache.lucene.index.IndexableField;

/**
 * @author lion
 * @email hl_0074@sina.com
 * @date 2014年4月16日
 */
public class BeanDocumentBuilder implements IDocumentBuilder {

	private Object target;

	public BeanDocumentBuilder(Object target) {

		this.target = target;
	}

	@SuppressWarnings("unchecked")
	@Override
	public Document build() {

		MapJ map = MapJ.mapBean(this.target);
		if (Map.class.isAssignableFrom(this.target.getClass())) {
			map = MapJ.map((Map<String, ? extends Object>) this.target);
		} else {
			map = MapJ.mapBean(this.target);
		}
		Document doc = new Document();
		for (String key : map.keySet()) {
			doc.add(getField(key, map.get(key)));
		}
		return doc;
	}

	private IndexableField getField(String key, Object value) {

		FieldType type;
		if (Date.class.isAssignableFrom(value.getClass())) {
			value = Formater.formatDate("yyyyMMddHHmmssSSS", (Date) value);
			type = StringField.TYPE_STORED;
		} else {
			type = getFieldType(value);
		}
		return new Field(key, String.valueOf(value), type);
	}

	private FieldType getFieldType(Object value) {

		if (CharSequence.class.isAssignableFrom(value.getClass())) { return TextField.TYPE_STORED; }
		if (Number.class.isAssignableFrom(value.getClass())) { return DoubleField.TYPE_STORED; }

		return StringField.TYPE_STORED;
	}

}
